package util;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.JwtBuilder;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.springframework.boot.context.properties.ConfigurationProperties;

import java.util.Date;

/**
 * Created by Administrator on 2021/6/2.
 */
@ConfigurationProperties("jwt.config")
public class JwtUtil {

    private String signName; //签名(盐值)
    private long ttl; //有效时间 单位毫秒

    public String getSignName() {
        return signName;
    }

    public void setSignName(String signName) {
        this.signName = signName;
    }

    public long getTtl() {
        return ttl;
    }

    public void setTtl(long ttl) {
        this.ttl = ttl;
    }

    /**
     * 生成token
     * @param id 用户id
     * @param name 用户名称
     * @param role 角色
     * @return
     */
    public String createToken(String id,String name,String role){
        long now = System.currentTimeMillis();
        JwtBuilder builder = Jwts.builder()
                .setId(id)
                .setSubject(name)
                .claim("role", role)
                .setIssuedAt(new Date(now)) //签发时间
                .setExpiration(new Date(now + ttl))     //失效时间
                .signWith(SignatureAlgorithm.HS256, signName);//算法和盐值
        String compact = builder.compact();
        return compact;
    }

    public Claims parseToken(String token){
        Claims claims = Jwts.parser()
                .setSigningKey(signName)
                .parseClaimsJws(token).getBody();
        return claims;
    }
}
